<?php

namespace app\model;

use GuzzleHttp\Client;
use think\Model;

class Message extends Model
{

    protected $connection = 'mysql';

    protected $pk = 'id';

    protected $name = 'message';

    public static function sendMiniPaysuccess($order)
    {
        $Openid = Openid::getWxappOpenidbyuid($order['uid']);
        $template_id = Config::getconfig('subscribemessage')['pay_tpl'];

        if ($order['ptype'] == 1) {
            $page = '/pagesA/my/myOrder/orderDetail?id=' . $order['id'];
        }

        if ($order['ptype'] == 2) {
            $page = '/pagesA/my/myOrder/yuyueDetail?id=' . $order['id'];
        }

        if (empty($order['remark'])) {
            $order['remark'] = '无';
        }

        if (!empty($Openid) && !empty($template_id)) {
            $app = Wxmini::make();

            $messagedata = [
                'template_id' => $template_id, // 所需下发的订阅模板id
                'touser' => $Openid,     // 接收者（用户）的 openid
                'page' => $page,       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                    'character_string1' => ["value" => $order['order_num_alias']],
                    'thing6' => ["value" => mb_substr($order['pay_subject'], 0, 20)],
                    'amount2' => ["value" => $order['total']],
                    'phrase17' => ["value" => '支付成功'],
                    'thing7' => ["value" => $order['remark']]
                ],
            ];
            $res = $app->subscribe_message->send($messagedata);
            //var_dump($res);
        }
    }

    public static function sendMiniItional($order)
    {
        $Openid = Openid::getWxappOpenidbyuid($order['uid']);
        $template_id = Config::getconfig('subscribemessage')['itional_tpl'];

        if ($order['ptype'] == 1) {
            $page = '/pagesA/my/myOrder/orderDetail?id=' . $order['id'];
        }

        if ($order['ptype'] == 2) {
            $page = '/pagesA/my/myOrder/yuyueDetail?id=' . $order['id'];
        }

        if (empty($order['remark'])) {
            $order['remark'] = '无';
        }

        if (!empty($Openid) && !empty($template_id)) {
            $app = Wxmini::make();

            $messagedata = [
                'template_id' => $template_id, // 所需下发的订阅模板id
                'touser' => $Openid,     // 接收者（用户）的 openid
                'page' => $page,       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                    'thing1' => ["value" => mb_substr($order['pay_subject'], 0, 20)],
                    'amount4' => ["value" => $order['additional']],
                    'thing6' => ["value" => '您有一个订单需要支付尾款，请及时支付']
                ],
            ];
            $res = $app->subscribe_message->send($messagedata);
        }
    }

    public static function sendMiniOrderComplete($order)
    {
        $Openid = Openid::getWxappOpenidbyuid($order['uid']);
        $template_id = Config::getconfig('subscribemessage')['complete_tpl'];

        if ($order['ptype'] == 1) {
            $page = '/pagesA/my/myOrder/orderDetail?id=' . $order['id'];
        }

        if ($order['ptype'] == 2) {
            $page = '/pagesA/my/myOrder/yuyueDetail?id=' . $order['id'];
        }

        if (empty($order['remark'])) {
            $order['remark'] = '无';
        }

        if (!empty($Openid) && !empty($template_id)) {
            $app = Wxmini::make();

            $messagedata = [
                'template_id' => $template_id, // 所需下发的订阅模板id
                'touser' => $Openid,     // 接收者（用户）的 openid
                'page' => $page,       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                    'character_string3' => ["value" => $order['order_num_alias']],
                    'thing1' => ["value" => mb_substr($order['pay_subject'], 0, 20)],
                    'amount6' => ["value" => $order['total']],
                    'phrase11' => ["value" => '服务已完成'],
                    'thing7' => ["value" => $order['remark']]
                ],
            ];

            $res = $app->subscribe_message->send($messagedata);
        }
    }

    public static function sendMiniStaff($order)
    {
        $Openid = Openid::getWxappOpenidbyuid($order['uid']);
        $template_id = Config::getconfig('subscribemessage')['staff_tpl'];

        if ($order['ptype'] == 1) {
            $page = '/pagesA/my/myOrder/orderDetail?id=' . $order['id'];
        }

        if ($order['ptype'] == 2) {
            $page = '/pagesA/my/myOrder/yuyueDetail?id=' . $order['id'];
        }

        if (empty($order['remark'])) {
            $order['remark'] = '无';
        }

        if (!empty($Openid) && !empty($template_id)) {
            $app = Wxmini::make();

            $uuid = OrderStaff::getuuid($order['id']);
            $Technical = Technical::getTitle($uuid);

            $messagedata = [
                'template_id' => $template_id, // 所需下发的订阅模板id
                'touser' => $Openid,     // 接收者（用户）的 openid
                'page' => $page,       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                    'thing3' => ["value" => mb_substr($order['pay_subject'], 0, 20)],
                    'name8' => ["value" => $Technical],
                    'thing12' => ["value" => $order['remark']]
                ],
            ];
            $res = $app->subscribe_message->send($messagedata);
            //var_dump($res);
        }
    }

    public static function itional_pay($orderInfo)
    {
        $messagetpl = Config::getconfig('messagetpl');
        $param['template_id'] = $messagetpl['pay_tpl'];
        if (empty($param['template_id'])) {
            $param['template_id'] = $messagetpl['default_tpl'];
        }

        $param['uuid'] = OrderStaff::getuuid($orderInfo['id']);

        $param['uid'] = UuidRelation::getuid($param['uuid']);
        if (empty($param['uid'])) {
            $param['uid'] = Member::get_uidByuuid($param['uuid']);
        }
        $param['title'] = '客户已支付尾款通知';
        $param['content'] = $orderInfo['pay_subject'] . '';
        $param['pages'] = '/pagesA/my/admintechnical/orderDetail';
        $param['query'] = 'id=' . $orderInfo['id'];

        if (self::send($param)) {
            self::sendmptplmessage($param);
            self::sendsmsmessage($param);
        };
    }

    public static function distribution($uuid, $orderInfo)
    {
        $messagetpl = Config::getconfig('messagetpl');
        $param['template_id'] = $messagetpl['technical_tpl'];
        if (empty($param['template_id'])) {
            $param['template_id'] = $messagetpl['default_tpl'];
        }

        $param['uuid'] = $uuid;

        $param['uid'] = UuidRelation::getuid($param['uuid']);
        if (empty($param['uid'])) {
            $param['uid'] = Member::get_uidByuuid($param['uuid']);
        }

        $param['title'] = '平台派单通知';
        $param['content'] = '您有一个新的平台订单，请及时处理';
        $param['pages'] = '/pagesA/my/admintechnical/orderDetail';
        $param['query'] = 'id=' . $orderInfo['id'];

        if (self::send($param)) {
            self::sendmptplmessage($param);
            self::sendsmsmessage($param);
        };
    }

    public static function undertake($orderInfo)
    {
        $messagetpl = Config::getconfig('messagetpl');
        $param['template_id'] = $messagetpl['undertake_tpl'];
        if (empty($param['template_id'])) {
            $param['template_id'] = $messagetpl['default_tpl'];
        }

        $Technical = Technical::gelist_bycity($orderInfo['shipping_city_name']);

        if (!empty($Technical)) {
            foreach ($Technical as $vo) {
                $param['uid'] = $vo['uid'];

                if (empty($param['uid'])) {
                    $param['uid'] = UuidRelation::getuid($vo['uuid']);
                }
                if (empty($param['uid'])) {
                    $param['uid'] = Member::get_uidByuuid($vo['uuid']);
                }
                $param['uuid'] = $vo['uuid'];
                $param['title'] = '平台推荐单通知';
                $param['content'] = '您有一个新的平台推荐订单，请及时处理';
                $param['pages'] = '/pagesA/my/publicOrder/order';

                $param['data']['keyword1'] = $orderInfo['order_num_alias'];
                $param['data']['keyword2'] = $orderInfo['pay_subject'];
                $param['data']['keyword3'] = $orderInfo['shipping_name'];
                $param['data']['keyword4'] = $orderInfo['shipping_tel'];
                $param['data']['remark'] = $param['content'];

                if (self::send($param)) {
                    self::sendmptplmessage($param);
                    self::sendsmsmessage($param);
                };
            }
        }
    }

    public static function orderPayNoticeAdmin($orderInfo)
    {
        $messagetpl = Config::getconfig('messagetpl');
        $param['template_id'] = $messagetpl['pay_tpl'];
        if (empty($param['template_id'])) {
            $param['template_id'] = $messagetpl['default_tpl'];
        }

        $where['users.uniacid'] = uniacid();
        $where['roles.is_admin'] = 1;
        $withJoin = [
            'roles' => ['title', 'is_admin'],
        ];
        $query = Users::where($where)->withJoin($withJoin, 'left');

        $query->whereNotNull('users.uuid');
        $query->where('users.uuid', '<>', '');

        $adminlist = $query->select()->toArray();

        if (!empty($adminlist)) {
            foreach ($adminlist as $vo) {

                $param['uid'] = UuidRelation::getuid($vo['uuid']);
                if (empty($param['uid'])) {
                    $param['uid'] = Member::get_uidByuuid($vo['uuid']);
                }


                $param['uuid'] = $vo['uuid'];
                $param['title'] = '订单支付成功';
                $param['content'] = '用户订单支付成功，请及时处理';
                $param['pages'] = '/pagesA/my/admin/orderDetail';

                $param['data']['keyword1'] = $orderInfo['shipping_name'];
                $param['data']['keyword2'] = $orderInfo['order_num_alias'];
                $param['data']['keyword3'] = $orderInfo['total'];
                $param['data']['keyword4'] = $orderInfo['pay_subject'];
                $param['data']['remark'] = $param['content'];

                $param['query'] = 'id=' . $orderInfo['id'];
                if (self::send($param)) {
                    self::sendmptplmessage($param);
                    self::sendsmsmessage($param);
                };
            }
        }
    }

    public static function send($param)
    {
        $data['uniacid'] = uniacid();
        $data['title'] = $param['title'];
        $data['content'] = $param['content'];
        $data['pages'] = $param['pages'] . '?' . $param['query'];
        $uid = $param['uid'];
        if (empty($uid)) {
            $uid = Member::get_uidByuuid($param['uuid']);
        }
        if (empty($uid)) {
            $uid = UuidRelation::getuuid($param['uuid']);
        }

        if (!empty($uid)) {
            $res = self::create($data);
            if ($res) {
                MessageBroadcast::create([
                    'message_id' => $res->id,
                    'sender' => 0,
                    'receiver' => $uid,
                    'is_read' => 0
                ]);
            }
        }

        return $res;
    }

    public static function sendmptplmessage($param)
    {

        if (!empty($param['uid'])) {
            $Openid = Openid::getMpOpenidbyuid($param['uid']);
        }
        if (empty($Openid)) {
            $Openid = Openid::getMpOpenidbyuuid($param['uuid']);
        }

        if (!empty($Openid)) {
            $miniConfig = Config::getconfig('miniprogram');
            $app = Wxmp::make();

            if ($param['query']) {
                $param['pages'] = $param['pages'] . '?' . $param['query'];
            }

            if (empty($param['data'])) {
                $param['data']['first'] = $param['title'];
                $param['data']['remark'] = $param['content'];
            }

            $messagedata = [
                'touser' => $Openid,
                'template_id' => trim($param['template_id']),
                'miniprogram' => [
                    'appid' => trim($miniConfig['app_id']),
                    'pagepath' => $param['pages'],
                ],
                'data' => $param['data'],
            ];

            $res = $app->template_message->send($messagedata);
            //var_dump($res);
            //Test::create(['info'=>serialize($res)]);

        }
    }

    public static function sendsmsmessage($param)
    {
        $retlink = Wxmini::urllink([
            'path' => $param['pages'],
            'query' => $param['query']
        ]);

        $phone = Technical::getTel($param['uuid']);
        if (!empty($phone)) {
            Sms::send_sms([
                'phone' => $phone,
                'param' => json_encode([
                    'customer' => "您有一个新的平台订单，请及时处理" . $retlink['url_link']
                ])
            ]);
        }
    }

    public static function apiCallMessage($phone, $templateId)
    {
        $commonConfig = Config::getconfig();
        $appId = $commonConfig['tencent_cloud_appid'];
        $secretId = $commonConfig['tencent_cloud_secretId'];
        $secretKey = $commonConfig['tencent_cloud_secretKey'];
        $host = "vms.tencentcloudapi.com";
        $service = "vms";
        $version = "2020-09-02";
        $action = "SendTtsVoice";
        $region = "ap-guangzhou";
        $timestamp = time();
        $algorithm = "TC3-HMAC-SHA256";
        $httpRequestMethod = "POST";
        $canonicalUri = "/";
        $canonicalQueryString = "";
        $canonicalHeaders = implode("\n", [
            "content-type:application/json; charset=utf-8",
            "host:" . $host,
            ""
        ]);
        $signedHeaders = implode(";", [
            "content-type",
            "host",
        ]);

        $body = [
            'TemplateId' => $templateId,
            'CalledNumber' => '+86' . $phone,
            'VoiceSdkAppid' => $appId,
            'TemplateParamSet' => []
        ];
        $payload = json_encode($body, JSON_UNESCAPED_UNICODE);
        $hashedRequestPayload = hash("SHA256", $payload);
        $canonicalRequest = $httpRequestMethod . "\n"
            . $canonicalUri . "\n"
            . $canonicalQueryString . "\n"
            . $canonicalHeaders . "\n"
            . $signedHeaders . "\n"
            . $hashedRequestPayload;
        $date = gmdate("Y-m-d", $timestamp);
        $credentialScope = $date . "/" . $service . "/tc3_request";
        $hashedCanonicalRequest = hash("SHA256", $canonicalRequest);
        $stringToSign = $algorithm . "\n"
            . $timestamp . "\n"
            . $credentialScope . "\n"
            . $hashedCanonicalRequest;
        $secretDate = hash_hmac("SHA256", $date, "TC3" . $secretKey, true);
        $secretService = hash_hmac("SHA256", $service, $secretDate, true);
        $secretSigning = hash_hmac("SHA256", "tc3_request", $secretService, true);
        $signature = hash_hmac("SHA256", $stringToSign, $secretSigning);
        $authorization = $algorithm
            . " Credential=" . $secretId . "/" . $credentialScope
            . ", SignedHeaders=" . $signedHeaders . ", Signature=" . $signature;
        $client = new Client();
        $response = $client->post('https://' . $host, [
            'headers' => [
                'Authorization' => $authorization,
                'Content-Type' => 'application/json; charset=utf-8',
                'Host' => $host,
                'X-TC-Action' => $action,
                'X-TC-Timestamp' => $timestamp,
                'X-TC-Version' => $version,
                'X-TC-Region' => $region,
            ],
            'json' => $body
        ]);
        $data = json_decode($response->getBody()->getContents(), true);
        return $data;
    }

    public static function sendCallMessage($uuid)
    {
        if ($uuid) {
            $phone = Technical::getTel($uuid);
            if ($phone) {
                $commonConfig = Config::getconfig();
                $templateId = $commonConfig['phone_notify_template_id'];
                return self::apiCallMessage($phone, $templateId);
            }
        }
    }
}
